#!/bin/bash

source build/hooks/tags.sh.inc # $REVISION_TAGS , $VERSION_TAG

PKG_DIR=build/packaging
VER=${VERSION_TAG//v}


echo "running post-commit hooks"

for revision_tag in $REVISION_TAGS
do echo "removing revision tag '$revision_tag'"
   git tag -d $revision_tag
done

echo "adding revision tag '$VERSION_TAG'"
git tag $VERSION_TAG


[ "$(git rev-parse --abbrev-ref HEAD)" == "packaging" ] || exit 0


tarball=$PKG_DIR/$VERSION_TAG.tar.gz
deb_tarball=loopidity_$VER.orig.tar.gz
deb_diffball=loopidity_$VER-1.diff.gz
rm $PKG_DIR/*.tar.gz*
git archive --prefix=$GITHUB_REPO_NAME-${VERSION_TAG//v}/ -o $tarball $VERSION_TAG


MD5SUM=$(md5sum $tarball | cut -d ' ' -f 1)
SHA1SUM="$(sha1sum $tarball | cut -d ' ' -f 1)                        "
SHA256SUM="$(sha256sum $tarball | cut -d ' ' -f 1)"
FILESIZE=$(wc -c $tarball | cut -d ' ' -f 1)
FAUXSUM='0123456789abcdef0123456789abcdef                                '
FAUXSIZE='1234567'

sed -i -e "s/^md5sums=.*$/md5sums=('$MD5SUM' SKIP)/"                   $PKG_DIR/PKGBUILD
tail -n 7 $PKG_DIR/loopidity.dsc | wc -c | xargs -I {} truncate        $PKG_DIR/loopidity.dsc -s -{} ;
(($(grep -c "pre-commit"        $PKG_DIR/loopidity.dsc) - 1)) && echo "$PKG_DIR/loopidity.dsc 0malformed" && exit 1
(($(grep -c "Checksums-Sha1:"   $PKG_DIR/loopidity.dsc)    )) && echo "$PKG_DIR/loopidity.dsc 1malformed"
(($(grep -c "Checksums-Sha256:" $PKG_DIR/loopidity.dsc)    )) && echo "$PKG_DIR/loopidity.dsc 2malformed"
(($(grep -c "Files:"            $PKG_DIR/loopidity.dsc)    )) && echo "$PKG_DIR/loopidity.dsc 3malformed"
echo "Checksums-Sha1:"                                              >> $PKG_DIR/loopidity.dsc
echo " $SHA1SUM $FILESIZE $deb_tarball"                             >> $PKG_DIR/loopidity.dsc
echo "Checksums-Sha256:"                                            >> $PKG_DIR/loopidity.dsc
echo " $SHA256SUM $FILESIZE $deb_tarball"                           >> $PKG_DIR/loopidity.dsc
echo "Files:"                                                       >> $PKG_DIR/loopidity.dsc
echo " $FAUXSUM $FAUXSIZE $deb_tarball"                             >> $PKG_DIR/loopidity.dsc
echo " $FAUXSUM $FAUXSIZE $deb_diffball"                            >> $PKG_DIR/loopidity.dsc

gpg --detach-sign --yes $tarball
gpg --detach-sign --yes $PKG_DIR/PKGBUILD
